package com.gcloud.mesh.monitor.timer;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gcloud.mesh.asset.dao.IaasDao;
import com.gcloud.mesh.asset.enums.DeviceType;
import com.gcloud.mesh.header.vo.asset.DeviceItemVo;
import com.gcloud.mesh.header.vo.supplier.DaHuaSupervisionSystemVo;
import com.gcloud.mesh.monitor.dao.StatisticsDao;
import com.gcloud.mesh.monitor.entity.StatisticsEntity;
import com.gcloud.mesh.supplier.dao.SupplierDao;
import com.gcloud.mesh.supplier.entity.SupplierEntity;
import com.gcloud.mesh.utils.SupplierSystemTypeUtil;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class DaHuaEnvirommentTimer {

	@Autowired
	StatisticsDao statisticsDao;

	@Autowired
	private IaasDao iaasDao;

	@Autowired
	private SupplierDao supplierDao;

	private static final String TYPE = "supervision_system_dahua";

	private static final String queryAllDeviceInfoAction = "/xtjk/webService/queryAllDeviceInfo.action";

	private static final String queryCollectDataAction = "/xtjk/webService/queryCollectData.action";

	private static List<Map<String, Object>> values = new ArrayList<Map<String, Object>>();

	private static Map<String, String> metrics = new HashMap<String, String>();

	private static Set<String> airDevices = new HashSet<String>(), boxDevices = new HashSet<String>(),
			upsDevices = new HashSet<String>();

	static {

		// TODO 补充大华动环指标
		metrics.put("回风平均温度", "environment.air_in_temperature");
		metrics.put("回风平均湿度", "environment.air_in_humidity");
		metrics.put("送风平均温度", "environment.air_out_temperature");
		metrics.put("送风平均湿度", "environment.air_out_humidity");
		metrics.put("送风温度设定", "environment.air_setting_temperature");

		metrics.put("总有功功率", "environment.distribution_box_power");

		metrics.put("A相输入电压", "environment.ups_in_voltage"); // UPS_输入电压
		metrics.put("输入频率", "environment.ups_in_frequency"); // UPS_输入频率
		metrics.put("电压", "environment.ups_out_voltage"); // UPS_输出电压
		metrics.put("机架输出频率", "environment.ups_out_frequency"); // UPS_输出频率
		metrics.put("模块温度", "environment.ups_temperature"); // UPS_电池温度
	}

	@Scheduled(fixedDelay = 1000 * 60 * 3)
	public void work() {

		List<SupplierEntity> suppliers = supplierDao.findAll().stream().filter(s -> TYPE.equals(s.getType()))
				.collect(Collectors.toList());
		for (SupplierEntity supplier : suppliers) {

			DaHuaSupervisionSystemVo obj = (DaHuaSupervisionSystemVo) SupplierSystemTypeUtil
					.getByName(supplier.getType(), supplier.getConfig());

			String hostIp = obj.getHostIp();
			String port = obj.getPort();

			this.getDevices(hostIp, port);
			this.getData(hostIp, port);

			if (values != null && values.size() > 0) {
				for (String key : metrics.keySet()) {
					StatisticsEntity entity = new StatisticsEntity();
					entity.setId(UUID.randomUUID().toString());
					entity.setMeter(metrics.get(key));

					entity.setTimestamp(new Date());

					for (String air : airDevices) {
						for (Map<String, Object> map : values) {
							Map<String, String> tmp = (Map<String, String>) map.get(key);
							entity.setValue(Double.valueOf(tmp.get(air)));
							List<DeviceItemVo> items = iaasDao.listDevice(supplier.getDatacenterId(),
									DeviceType.AIR_CONDITION.getNo());
							for (DeviceItemVo item : items) {
								if (airDevices.contains(item.getDeviceId())) {
									entity.setResourceId(item.getId());
								}
							}
						}
					}

					for (String air : boxDevices) {
						for (Map<String, Object> map : values) {
							Map<String, String> tmp = (Map<String, String>) map.get(key);
							entity.setValue(Double.valueOf(tmp.get(air)));
							List<DeviceItemVo> items = iaasDao.listDevice(supplier.getDatacenterId(),
									DeviceType.DISTRIBUTION_BOX.getNo());
							for (DeviceItemVo item : items) {
								if (boxDevices.contains(item.getDeviceId())) {
									entity.setResourceId(item.getId());
								}
							}
						}
					}

					for (String air : upsDevices) {
						for (Map<String, Object> map : values) {
							Map<String, String> tmp = (Map<String, String>) map.get(key);
							entity.setValue(Double.valueOf(tmp.get(air)));
							List<DeviceItemVo> items = iaasDao.listDevice(supplier.getDatacenterId(),
									DeviceType.UPS.getNo());
							for (DeviceItemVo item : items) {
								if (upsDevices.contains(item.getDeviceId())) {
									entity.setResourceId(item.getId());
								}
							}
						}
					}

					statisticsDao.save(entity);
				}
			} else {
				log.debug("[DaHuaEnvironmentTimer] 未采集到动环数据!");
			}
		}
	}

	private void getDevices(String hostIp, String port) {
		String url = "http://" + hostIp + ":" + port + queryAllDeviceInfoAction;
		RestTemplate restTemplate = new RestTemplate();
		String res = restTemplate.getForEntity(url, String.class).getBody();
		JSONObject resJ = JSONObject.parseObject(res);
		JSONArray jsonArray = resJ.getJSONArray("rows");
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject json = jsonArray.getJSONObject(i);
			if (json.getString("deviceCategroy").equals("2")) {
				airDevices.add(json.getString("id"));
			} else if (json.getString("deviceCategroy").equals("3")) {
				upsDevices.add(json.getString("id"));
			} else if (json.getString("deviceCategroy").equals("1")) {
				boxDevices.add(json.getString("id"));
			}
		}
	}

	private void getData(String hostIp, String port) {

		String url = "http://" + hostIp + ":" + port + queryCollectDataAction;
		RestTemplate restTemplate = new RestTemplate();

		restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));

		String res = restTemplate.getForEntity(url, String.class).getBody();
		JSONObject resJ = JSONObject.parseObject(res);
		JSONArray jsonArray = resJ.getJSONArray("rows");

		for (int i = 0; i < jsonArray.size(); i++) {

			JSONObject json = jsonArray.getJSONObject(i);
			if (metrics.containsKey(json.getString("paramName"))) {
				Map<String, Object> tmp = new HashMap<String, Object>();
				Map<String, String> temp = new HashMap<String, String>();
				temp.put(json.getString("deviceId"), json.getString("collectionData"));
				tmp.put(json.getString("paramName"), temp);

				values.add(tmp);
			}
		}
	}
}
